/*******************************************************************************
 * Copyright (c) 2000, 2004 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials 
 * are made available under the terms of the Common Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/cpl-v10.html
 * 
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
module dwt.widgets.trayitem;


private import dwt.dwt;

private import dwt.widgets.display;
private import dwt.widgets.event;
public import dwt.widgets.item;
private import dwt.widgets.tray;
private import dwt.widgets.typedlistener;
private import dwt.events.listeners;
private import dwt.graphics.imagedata;
private import dwt.graphics.image;
private import dwt.util.util;
private import dwt.events.events;
private import dwt.util.eventhandler;
private import dwt.internal.win32.os;

/**
 * Instances of this class represent icons that can be placed on the
 * system tray or task bar status area.
 *
 * <dl>
 * <dt><b>Styles:</b></dt>
 * <dd>(none)</dd>
 * <dt><b>Events:</b></dt>
 * <dd>DefaultSelection, MenuDetect, Selection</dd>
 * </dl>
 * <p>
 * IMPORTANT: This class is <em>not</em> intended to be subclassed.
 * </p>
 * 
 * @since 3.0
 */
public class TrayItem : Item {
	Tray parent;
	int id;
	Image image2;
	char[] toolTipText;
	boolean visible = true;
	
/**
 * Constructs a new instance of this class given its parent
 * (which must be a <code>Tray</code>) and a style value
 * describing its behavior and appearance. The item is added
 * to the end of the items maintained by its parent.
 * <p>
 * The style value is either one of the style constants defined in
 * class <code>SWT</code> which is applicable to instances of this
 * class, or must be built by <em>bitwise OR</em>'ing together 
 * (that is, using the <code>int</code> "|" operator) two or more
 * of those <code>SWT</code> style constants. The class description
 * lists the style constants that are applicable to the class.
 * Style bits are also inherited from superclasses.
 * </p>
 *
 * @param parent a composite control which will be the parent of the new instance (cannot be null)
 * @param style the style of control to construct
 *
 * @exception IllegalArgumentException <ul>
 *    <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
 * </ul>
 * @exception SWTException <ul>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the parent</li>
 *    <li>ERROR_INVALID_SUBCLASS - if this class is not an allowed subclass</li>
 * </ul>
 *
 * @see SWT
 * @see Widget#checkSubclass
 * @see Widget#getStyle
 */
public this (Tray parent, int style) {
	super (parent, style);
	this.parent = parent;
	parent.createItem (this, parent.getItemCount ());
	createWidget ();
}

/**
 * Adds the listener to the collection of listeners who will
 * be notified when the receiver is selected, by sending
 * it one of the messages defined in the <code>SelectionListener</code>
 * interface.
 * <p>
 * <code>widgetSelected</code> is called when the receiver is selected
 * <code>widgetDefaultSelected</code> is called when the receiver is double-clicked
 * </p>
 *
 * @param listener the listener which should be notified
 *
 * @exception IllegalArgumentException <ul>
 *    <li>ERROR_NULL_ARGUMENT - if the listener is null</li>
 * </ul>
 * @exception SWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 *
 * @see SelectionListener
 * @see #removeSelectionListener
 * @see SelectionEvent
 */
public void addSelectionListener(SelectionListener listener) {
	checkWidget ();
	if (listener is null) error(__FILE__, __LINE__, DWT.ERROR_NULL_ARGUMENT);
	TypedListener typedListener = new TypedListener (listener);
	addListener (DWT.Selection,typedListener);
	addListener (DWT.DefaultSelection,typedListener);
}

void createWidget () {
	version(WinCE) { return; }
	NOTIFYICONDATA iconData;
	iconData.cbSize = NOTIFYICONDATA.sizeof;
	iconData.uID = id = display.nextTrayId++;
	iconData.hWnd = display.hwndMessage;
	iconData.uFlags = OS.NIF_MESSAGE;
	iconData.uCallbackMessage = Display.DWT_TRAYICONMSG;
	OS.Shell_NotifyIcon (OS.NIM_ADD, &iconData);
}

/**
 * Returns the receiver's tool tip text, or null if it has
 * not been set.
 *
 * @return the receiver's tool tip text
 *
 * @exception SWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 */
public char[] getToolTipText () {
	checkWidget ();
	return toolTipText;
}

/**
 * Returns <code>true</code> if the receiver is visible and 
 * <code>false</code> otherwise.
 *
 * @return the receiver's visibility
 *
 * @exception SWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 */
public boolean getVisible () {
	checkWidget ();
	return visible;
}

int messageProc (HWND hwnd, uint msg, int wParam, int lParam) {
	/*
	* Feature in Windows.  When the user clicks on the tray
	* icon, another application may be the foreground window.
	* This means that the event loop is not running and can
	* cause problems.  For example, if a menu is shown, when
	* the user clicks outside of the menu to cancel it, the
	* menu is not hidden until an event is processed.  If
	* another application is the foreground window, then the
	* menu is not hidden.  The fix is to force the tray icon
	* message window to the foreground when sending an event.
	*/
	switch (lParam) {
		case OS.WM_LBUTTONDOWN:
			if (hooks (DWT.Selection)) {
				OS.SetForegroundWindow (hwnd);
				postEvent (DWT.Selection);
			}
			break;
		case OS.WM_LBUTTONDBLCLK:
		case OS.WM_RBUTTONDBLCLK:
			if (hooks (DWT.DefaultSelection)) {
				OS.SetForegroundWindow (hwnd);
				postEvent (DWT.DefaultSelection);
			}
			break;
		case OS.WM_RBUTTONUP: {
			if (hooks (DWT.MenuDetect)) {
				OS.SetForegroundWindow (hwnd);
				sendEvent (DWT.MenuDetect);
				// widget could be disposed at this point
				if (isDisposed()) return 0;
			}
			break;
		}
		default : break;
	}
	display.wakeThread ();
	return 0;
}

void recreate () {
	createWidget ();
	if (!visible) setVisible (false);
	if (text !is null ) setText (text);
	if (image !is null) setImage (image);
	if (toolTipText !is null) setToolTipText (toolTipText);
}

void releaseChild () {
	super.releaseChild ();
	parent.destroyItem (this);
}

void releaseWidget () {
	super.releaseWidget ();
	if (image2 !is null) image2.dispose ();
	image2 = null;
	toolTipText = null;
	version(WinCE) { return; }
	NOTIFYICONDATA iconData;
	iconData.cbSize = NOTIFYICONDATA.sizeof;
	iconData.uID = id;
	iconData.hWnd = display.hwndMessage;
	OS.Shell_NotifyIcon (OS.NIM_DELETE, &iconData);
}
	
/**
 * Removes the listener from the collection of listeners who will
 * be notified when the receiver is selected.
 *
 * @param listener the listener which should no longer be notified
 *
 * @exception IllegalArgumentException <ul>
 *    <li>ERROR_NULL_ARGUMENT - if the listener is null</li>
 * </ul>
 * @exception SWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 *
 * @see SelectionListener
 * @see #addSelectionListener
 */
public void removeSelectionListener(SelectionListener listener) {
	checkWidget ();
	if (listener is null) error(__FILE__, __LINE__, DWT.ERROR_NULL_ARGUMENT);
	if (eventTable is null) return;
	eventTable.unhook (DWT.Selection, listener);
	eventTable.unhook (DWT.DefaultSelection,listener);	
}

/**
 * Sets the receiver's image.
 *
 * @param image the new image
 *
 * @exception IllegalArgumentException <ul>
 *    <li>ERROR_INVALID_ARGUMENT - if the image has been disposed</li>
 * </ul>
 * @exception SWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 */
public void setImage (Image image) {
	checkWidget ();
	if (image !is null && image.isDisposed ()) error(__FILE__, __LINE__, DWT.ERROR_INVALID_ARGUMENT);
	super.setImage (image);
	version(WinCE) { return; }
	if (image2 !is null) image2.dispose ();
	image2 = null;
	HICON hIcon = null;
	Image icon = image;
	if (icon !is null) {
		switch (icon.type) {
			case DWT.BITMAP:
				ImageData data = icon.getImageData ();
				ImageData mask = data.getTransparencyMask ();
				image2 = new Image (display, data, mask);
				hIcon = image2.handle;
				break;
			case DWT.ICON:
				hIcon = icon.handle;
				break;
			default : break;
		}
	}
	NOTIFYICONDATA iconData;
	iconData.cbSize = NOTIFYICONDATA.sizeof;
	iconData.uID = id;
	iconData.hWnd = display.hwndMessage;
	iconData.hIcon = hIcon;
	iconData.uFlags = OS.NIF_ICON;
	OS.Shell_NotifyIcon (OS.NIM_MODIFY, &iconData);
}

/**
 * Sets the receiver's tool tip text to the argument, which
 * may be null indicating that no tool tip text should be shown.
 *
 * @param value the new tool tip text (or null)
 *
 * @exception SWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 */
public void setToolTipText (char[] value) {
	checkWidget ();
	toolTipText = value;
	version(WinCE) { return; }
	NOTIFYICONDATA iconData;
	TCHAR[] buffer = Converter.StrToTCHARs(toolTipText[]);
	/*
	* Note that the size of the szTip field is different
	* in version 5.0 of shell32.dll.
	*/
	uint len = OS.SHELL32_MAJOR < 5 ? 64 : 128;
	len = Math.min (len - 1, buffer.length);
	iconData.szTip[0..len] = buffer[0..len];
	// <Shawn> fix : the garbage characters in tooltip
	iconData.szTip[len] = 0;
	
	iconData.cbSize = NOTIFYICONDATA.sizeof;
	iconData.uID = id;
	iconData.hWnd = display.hwndMessage;
	iconData.uFlags = OS.NIF_TIP;
	OS.Shell_NotifyIcon (OS.NIM_MODIFY, &iconData);
}

/**
 * Makes the receiver visible if the argument is <code>true</code>,
 * and makes it invisible otherwise. 
 *
 * @param visible the new visibility state
 *
 * @exception SWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 */
public void setVisible (boolean visible) {
	checkWidget ();
	if (this.visible == visible) return;
	if (visible) {
		/*
		* It is possible (but unlikely), that application
		* code could have disposed the widget in the show
		* event.  If this happens, just return.
		*/
		sendEvent (DWT.Show);
		if (isDisposed ()) return;
	}
	this.visible = visible;
	version(WinCE) { } else {
		NOTIFYICONDATA iconData;
		iconData.cbSize = NOTIFYICONDATA.sizeof;
		iconData.uID = id;
		iconData.hWnd = display.hwndMessage;
		if (OS.SHELL32_MAJOR < 5) {
			if (visible) {
				iconData.uFlags = OS.NIF_MESSAGE;
				iconData.uCallbackMessage = Display.DWT_TRAYICONMSG;
				OS.Shell_NotifyIcon (OS.NIM_ADD, &iconData);
				setImage (image);
				setToolTipText (toolTipText);
			} else {
				OS.Shell_NotifyIcon (OS.NIM_DELETE, &iconData);
			}
		} else {
			iconData.uFlags = OS.NIF_STATE;
			iconData.dwState = visible ? 0 : OS.NIS_HIDDEN;
			iconData.dwStateMask = OS.NIS_HIDDEN;
			OS.Shell_NotifyIcon (OS.NIM_MODIFY, &iconData);
		}
	}
	if (!visible) sendEvent (DWT.Hide);
}


// Event Handler
public void handleSelection(Object customData, void delegate(SelectionEvent) func){
	handleEvent(new SelectionHandler(customData, DWT.Selection, func));
}
public void handleDefaultSelection(Object customData, void delegate(SelectionEvent) func) {
	handleEvent(new SelectionHandler(customData, DWT.DefaultSelection, func));
}


}
